<template>
  <div class="membership-plans-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" :inline="true">
        <el-form-item label="套餐名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入套餐名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="套餐类型">
          <el-select v-model="searchForm.type" placeholder="请选择套餐类型" clearable style="width: 150px">
            <el-option label="月度会员" value="monthly" />
            <el-option label="季度会员" value="quarterly" />
            <el-option label="年度会员" value="yearly" />
            <el-option label="终身会员" value="lifetime" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
          <el-button @click="resetSearch" :icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="operation-card">
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd" :icon="Plus">新增套餐</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            :disabled="!multipleSelection.length"
            @click="handleBatchDelete"
            :icon="Delete"
          >
            批量删除
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="套餐名称" min-width="150" />
        <el-table-column prop="type" label="套餐类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="有效期" width="100">
          <template #default="{ row }">
            {{ getDurationText(row.type, row.duration) }}
          </template>
        </el-table-column>
        <el-table-column prop="originalPrice" label="原价" width="100">
          <template #default="{ row }">
            ¥{{ row.originalPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentPrice" label="现价" width="100">
          <template #default="{ row }">
            <span style="color: #f56c6c; font-weight: bold">¥{{ row.currentPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="features" label="特权功能" min-width="200">
          <template #default="{ row }">
            <el-tag
              v-for="feature in row.features.slice(0, 3)"
              :key="feature"
              size="small"
              style="margin-right: 5px; margin-bottom: 2px"
            >
              {{ feature }}
            </el-tag>
            <span v-if="row.features.length > 3" style="color: #909399">
              等{{ row.features.length }}项特权
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="80" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)" :icon="Edit">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)" :icon="Delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="套餐名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入套餐名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="套餐类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择套餐类型" style="width: 100%">
                <el-option label="月度会员" value="monthly" />
                <el-option label="季度会员" value="quarterly" />
                <el-option label="年度会员" value="yearly" />
                <el-option label="终身会员" value="lifetime" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20" v-if="formData.type !== 'lifetime'">
          <el-col :span="12">
            <el-form-item label="有效期(天)" prop="duration">
              <el-input-number
                v-model="formData.duration"
                :min="1"
                :max="3650"
                style="width: 100%"
                placeholder="请输入有效期天数"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number
                v-model="formData.originalPrice"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入原价"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="现价" prop="currentPrice">
              <el-input-number
                v-model="formData.currentPrice"
                :min="0"
                :precision="2"
                style="width: 100%"
                placeholder="请输入现价"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="套餐描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入套餐描述"
          />
        </el-form-item>

        <el-form-item label="特权功能" prop="features">
          <div class="features-container">
            <el-tag
              v-for="(feature, index) in formData.features"
              :key="index"
              closable
              @close="removeFeature(index)"
              style="margin-right: 10px; margin-bottom: 10px"
            >
              {{ feature }}
            </el-tag>
            <el-input
              v-if="inputVisible"
              ref="inputRef"
              v-model="inputValue"
              size="small"
              style="width: 120px"
              @keyup.enter="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button v-else size="small" @click="showInput">+ 添加特权</el-button>
          </div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number
                v-model="formData.sort"
                :min="0"
                style="width: 100%"
                placeholder="数字越小排序越靠前"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :label="1">启用</el-radio>
                <el-radio :label="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Delete, Edit } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const multipleSelection = ref([])
const inputVisible = ref(false)
const inputValue = ref('')
const inputRef = ref(null)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  status: ''
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 表格数据
const tableData = ref([])

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  type: '',
  duration: 30,
  originalPrice: 0,
  currentPrice: 0,
  description: '',
  features: [],
  sort: 0,
  status: 1
})

// 表单引用
const formRef = ref(null)

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择套餐类型', trigger: 'change' }
  ],
  originalPrice: [
    { required: true, message: '请输入原价', trigger: 'blur' }
  ],
  currentPrice: [
    { required: true, message: '请输入现价', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入套餐描述', trigger: 'blur' }
  ]
}

// 计算属性
const dialogTitle = computed(() => {
  return formData.id ? '编辑套餐' : '新增套餐'
})

// 生命周期
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 模拟API调用
    setTimeout(() => {
      tableData.value = [
        {
          id: 1,
          name: '月度会员',
          type: 'monthly',
          duration: 30,
          originalPrice: 99.00,
          currentPrice: 79.00,
          description: '享受一个月的会员特权',
          features: ['无限制学习', '专属客服', '学习报告', '优先答疑'],
          sort: 1,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 2,
          name: '季度会员',
          type: 'quarterly',
          duration: 90,
          originalPrice: 297.00,
          currentPrice: 199.00,
          description: '享受三个月的会员特权，更优惠',
          features: ['无限制学习', '专属客服', '学习报告', '优先答疑', '专属社群'],
          sort: 2,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 3,
          name: '年度会员',
          type: 'yearly',
          duration: 365,
          originalPrice: 1188.00,
          currentPrice: 599.00,
          description: '享受一年的会员特权，最划算',
          features: ['无限制学习', '专属客服', '学习报告', '优先答疑', '专属社群', '线下活动'],
          sort: 3,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        },
        {
          id: 4,
          name: '终身会员',
          type: 'lifetime',
          duration: 0,
          originalPrice: 2999.00,
          currentPrice: 1999.00,
          description: '一次购买，终身享受所有特权',
          features: ['无限制学习', '专属客服', '学习报告', '优先答疑', '专属社群', '线下活动', '一对一指导'],
          sort: 4,
          status: 1,
          createTime: '2024-01-15 10:30:00'
        }
      ]
      pagination.total = 4
      loading.value = false
    }, 500)
  } catch (error) {
    console.error('加载数据失败:', error)
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增
const handleAdd = () => {
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  resetForm()
  Object.keys(formData).forEach(key => {
    if (row.hasOwnProperty(key)) {
      formData[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除套餐"${row.name}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    ElMessage.success('删除成功')
    loadData()
  })
}

// 批量删除
const handleBatchDelete = () => {
  const ids = multipleSelection.value.map(item => item.id)
  ElMessageBox.confirm(
    `确定要删除选中的${ids.length}个套餐吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量删除操作
    ElMessage.success('批量删除成功')
    loadData()
  })
}

// 状态切换
const handleStatusChange = (row) => {
  const status = row.status ? '启用' : '禁用'
  ElMessage.success(`${status}成功`)
}

// 选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection
}

// 分页大小变化
const handleSizeChange = (size) => {
  pagination.size = size
  loadData()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pagination.page = page
  loadData()
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      // 模拟提交操作
      setTimeout(() => {
        ElMessage.success(formData.id ? '编辑成功' : '新增成功')
        dialogVisible.value = false
        submitLoading.value = false
        loadData()
      }, 1000)
    }
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    if (key === 'features') {
      formData[key] = []
    } else if (key === 'status') {
      formData[key] = 1
    } else if (key === 'duration') {
      formData[key] = 30
    } else if (key === 'sort' || key === 'originalPrice' || key === 'currentPrice') {
      formData[key] = 0
    } else {
      formData[key] = key === 'id' ? null : ''
    }
  })
}

// 获取类型标签类型
const getTypeTagType = (type) => {
  const typeMap = {
    monthly: '',
    quarterly: 'success',
    yearly: 'warning',
    lifetime: 'danger'
  }
  return typeMap[type] || ''
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    monthly: '月度会员',
    quarterly: '季度会员',
    yearly: '年度会员',
    lifetime: '终身会员'
  }
  return typeMap[type] || type
}

// 获取有效期文本
const getDurationText = (type, duration) => {
  if (type === 'lifetime') {
    return '终身'
  }
  return `${duration}天`
}

// 移除特权
const removeFeature = (index) => {
  formData.features.splice(index, 1)
}

// 显示输入框
const showInput = () => {
  inputVisible.value = true
  nextTick(() => {
    inputRef.value?.focus()
  })
}

// 确认输入
const handleInputConfirm = () => {
  if (inputValue.value && !formData.features.includes(inputValue.value)) {
    formData.features.push(inputValue.value)
  }
  inputVisible.value = false
  inputValue.value = ''
}
</script>

<style scoped>
.membership-plans-container {
  padding: 20px;
}

.search-card,
.operation-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.features-container {
  min-height: 40px;
}

.dialog-footer {
  text-align: right;
}
</style>